<?php

namespace common\models\shop;

use Yii;
use common\helpers\Url;
use common\models\spread\SpreadType;

/**
 * This is the model class for table "{{%shop_activity}}".
 *
 * @property int $id
 * @property string $name 活动名称
 * @property string $description 说明
 * @property int $begin_time 活动开始时间
 * @property int $end_time 活动结束时间
 * @property string $template 活动展示模板
 * @property int $status 活动状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class ShopSpreadActivity extends \common\models\spread\SpreadActivity {

    public function getProducts() {
        return $this->hasMany(ShopActivityProduct::className(), ['activity_id' => 'id']);
    }

    public static function activeProducts($id = null) {
        $query = static::findActive(null, static::STATUS_ACTIVE)
        ->andFilterWhere(['id' => $id])
        ->andFilterWhere(['>=', 'end_time', time()])
        ->orderBy(['updated_at' => SORT_DESC]);

        $query->innerJoinWith([
            'type type' => function ($query) {
                $query->active(SpreadType::STATUS_ACTIVE)->andWhere(['type.name' => static::TYPE_SHOP]);
            }
        ]);

        $model = $query->one();
        if (!$model) {
            return null;
        }
        return $model->toArray();
    }

    public function fields() {
        return [
            'id',
            'name',
            'description',
            'begin_time',
            'end_time',
            'link',
            'products' => function() {
                return $this->getProducts()->limit(3)->all();
            },
        ];
    }

}
